import os,sys
import hashlib
import optparse

def md5(fileName, excludeLine="", includeLine=""):
    MAX_LENGHT_ONCE = 10*1024*1024
    m = hashlib.md5()
    try:
        fd = open(fileName,"rb")
    except IOError:
        print("Unable to open the file:", filename)
        return
    eachLine = fd.read(MAX_LENGHT_ONCE) 
    prev = None
    while eachLine:
        if excludeLine and eachLine.startswith(excludeLine):
            continue   
        m.update(eachLine)
        eachLine = fd.read(MAX_LENGHT_ONCE)
    return m.hexdigest()


if __name__ == '__main__':
    p = optparse.OptionParser(description='md5 caluate/check/creat',
                          prog='md5.py',
                          version='%prog v0.1',
                          usage='%prog [options] File/Dir [File/Dir...]')
    p.add_option('--check', '-c', action="store_true", help='check a .md5 file', dest="check")
    (options, args) = p.parse_args()
    if options.check == True:
        md5s = open(args[0],'r').readlines()
        dirpath = os.path.split(args[0])[0]
        for m in md5s:
            m = m.strip()
            if m.startswith(';'):
                continue
            md5hash = m[:m.find(' ')]
            filename = m[m.find(' '):].strip()
            if filename[0] == '*':
                filename = filename[1:]
            path = os.path.join(dirpath, filename)
            if md5hash == md5(path):
                print("Pass......", filename)
            else:
                print("Fail......", filename)            
        sys.exit()
        
    for a in args:
        if os.path.isfile(a) == True :
            print(md5(a), "*%s"%os.path.split(a)[1])
        if os.path.isdir(a) == True :
            files = FileHostCommon.walkDir(a)
            folder = os.path.split(a)[1]
            for f in files:
                md5hash = md5(f)
                print(md5hash, "*%s" % os.path.join(folder,f.replace(a,'')[1:]))
                
        

        
